<template>
  <back-dialog-base
    :title="title"
    :visible="visibleDialog"
    width="488px"
    @onCommit="handleSubmit"
  >
    <template #content>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入..."></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="description">
          <el-input
            v-model="form.description"
            placeholder="请输入..."
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
  </back-dialog-base>
</template>

<script setup>
import { reactive, defineProps, ref, defineEmits, watch } from 'vue'
import BackDialogBase from '@/components/BackDialogBase'
import { saveDept } from '@/api/dept'
import { message } from '@/utils/message'
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visibleDialog: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['onReload'])
const formRef = ref(null)
const form = reactive({
  name: '',
  description: ''
})

const rules = reactive({
  name: [
    {
      required: true,
      message: '部门名称不能为空',
      trigger: 'blur'
    }
  ],
  description: [
    {
      required: true,
      message: '描述不能为空',
      trigger: 'blur'
    }
  ]
})

const handleSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      save(Object.assign(props.rowData, form))
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const save = async (data) => {
  const res = await saveDept(data)
  if (res && res.id) {
    message({ type: 'success', message: '部门添加成功!' })
    clearForm()
    emits('onReload')
  }
}

const clearForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.name = ''
  form.description = ''
}

watch(
  () => props.rowData,
  () => {
    form.name = props.rowData.name
    form.description = props.rowData.description
  }
)
</script>

<style lang="scss" scoped>
.font {
  font-size: 16px;
  font-family: Source Han Sans CN;
  color: #333333;
}
:deep(.el-date-editor.el-input, .el-date-editor.el-input__inner) {
  width: 100%;
}
.el-dialog__header{
  background-color: rgba(24, 144, 255, 1);
}
</style>
